import { useState } from "react";
import { connect, Link, history } from 'umi';
import { Tabs, Input, Skeleton, PageHeader, Descriptions, message, Tooltip ,Modal} from 'antd';
import { ClockCircleOutlined } from '@ant-design/icons'
import styles from './style.less';
import { useEffect } from "react";
import { DevStatus } from '../../ProjectDev/DevPage'
import RichText, { RichTextEdit } from '@/components/RichText'
import EditAble from '@/components/EditAble';
import ArrayUtils from '@/utils/ArrayUtils';
import { PROJECT_DEV_STATUS } from '@/consts/project'
import { formetTime } from '@/utils/dateUtils'
import UserBrief from '@/components/UserBrief';
import RiskItem from './RiskItem'
import { update, getDetail,deleteDev,updateIsArchived } from '@/services/project/dev'
import TextButton from '@/components/TextButton'
import ProjectProdSelect from '@/pages/projects/components/ProjectProduct/ProjectProdSelect'
import TaskPage from '@/pages/projects/components/ProjectTask/TaskPage'
import ProjectComment from '@/pages/projects/components/ProjectComment'
import ProjectItemLog from '@/pages/projects/components/ProjectItemLog'
import TaskGantt from '@/pages/projects/components/ProjectTask/TaskGantt'
import ActionDropdown from '@/components/ActionDropdown';
const { Search } = Input;
const { TabPane } = Tabs;


const DevDetail = (props) => {

    const {
        projectId,
        devId,
        routeTabKey,
        projectPermission,
    } = props

    const [tabKey, setTabKey] = useState()
    const [isDetailTextEditFlag, setIsDetailTextEditFlag] = useState();
    const [isRiskItemEditFlag, setIsRiskItemEditFlag] = useState();
    const [isProdEditFlag, setIsProdEditFlag] = useState(false);
    const [devDetail, setDevDetail] = useState({})
    const [projectLogUpdate, setProjectLogUpdate] = useState(0)
    const [permission, setPermission] = useState();

    useEffect(() => {
        getDetail(projectId, devId).then(({ data }) => {
            setDevDetail(data)
        })
    }, [])

    useEffect(() => {
        setPermission({
            ...projectPermission?.dev
        })
    }, [projectPermission])

    useEffect(() => {
        if (routeTabKey) {
            setTabKey(routeTabKey)
        }
    }, [routeTabKey])

    if (!devDetail || devDetail.id !== devId) {
        return <div className={styles.detailContainer}><Skeleton></Skeleton></div>
    }

    const rightEntra = (<></>)

    const onChangeTabSwitch = (tabKey) => {
        if (tabKey === "log") {
            setProjectLogUpdate(projectLogUpdate + 1)
        }
        setTabKey(tabKey)
        history.replace(`/projects/${projectId}/dev/${devId}/${tabKey}`)
    }

    const updateName = (name) => {
        updateDev({
            name: name,
            oldData: {
                name: devDetail.name
            }
        })
        devDetail.name = name;
        setDevDetail({ ...devDetail })
    }

    const updateProjectUser = (userId, user) => {
        updateDev({
            userId: userId,
            payload: {
                userId: user?.nickName
            },
            oldData: {
                name: devDetail.userId,
                payload: {
                    userId: devDetail.user?.nickName
                }
            }
        })
        devDetail.userId = userId;
        devDetail.user = user;
        setDevDetail({ ...devDetail })
    }

    const updateStatus = (status) => {
        updateDev({
            status: status,
            oldData: {
                status: devDetail.status
            }
        })
        devDetail.status = status;
        setDevDetail({ ...devDetail })
    }

    const updateProjectProd = (id, item) => {
        updateDev({
            projectProdItemId: id,
            payload: {
                projectProdItemId: item?.name,
            },
            oldData: {
                projectProdItemId: devDetail.projectProdItemId,
                payload: {
                    projectProdItemId: devDetail.projectProdItem?.name,
                },
            }
        })
        devDetail.projectProdItemId = id;
        devDetail.projectProdItem = item
        setDevDetail({ ...devDetail })
    }

    const updateActualStartDate = (dateTime) => {
        updateDev({
            actualStartDate: dateTime,
            oldData: {
                actualStartDate: devDetail.actualStartDate
            }
        })
        devDetail.actualStartDate = dateTime;
        setDevDetail({ ...devDetail })
    }

    const updateActualSubmitQaDate = (dateTime) => {
        updateDev({
            actualSubmitQaDate: dateTime,
            oldData: {
                actualSubmitQaDate: devDetail.actualSubmitQaDate
            }
        })
        devDetail.actualSubmitQaDate = dateTime;
        setDevDetail({ ...devDetail })
    }

    const updateActualReleaseTime = (dateTime) => {
        updateDev({
            actualReleaseDate: dateTime,
            oldData: {
                actualReleaseDate: devDetail.actualReleaseDate
            }
        })
        devDetail.actualReleaseDate = dateTime;
        setDevDetail({ ...devDetail })
    }

    const updateDemandCheckDate = (dateTime) => {
        updateDev({
            demandCheckDate: dateTime,
            oldData: {
                demandCheckDate: devDetail.demandCheckDate
            }
        })
        devDetail.demandCheckDate = dateTime;
        setDevDetail({ ...devDetail })
    }
    const updateProjectDesc = (description) => {
        updateDev({
            description: description,
            oldData: {
                description: devDetail.description
            }
        })
        devDetail.description = description;
        setDevDetail({ ...devDetail })
    }

    const updateDevContent = (content) => {
        const oldDataContent = {
            content: {
                text: devDetail.content.text
            }
        };
        updateDev({
            content: content,
            oldData: oldDataContent
        })
        devDetail.content = content;
        setDevDetail({ ...devDetail })
        setIsDetailTextEditFlag(false)
    }

    const updateRiskItems = (riskItems) => {
        updateDev({
            riskItems: riskItems,
            oldData: {
                riskItems: devDetail.riskItems
            }
        })
        devDetail.riskItems = riskItems;
        setDevDetail({ ...devDetail })
        setIsRiskItemEditFlag(false)
    }

    const updateDev = (values) => {
        update(devDetail.projectId, devDetail.id, values).then(({ success }) => {
            if (success) {
                message.success("保存成功")
            }
            setProjectLogUpdate(projectLogUpdate + 1)
        })
    }

    const updatItemIsArchived = (isArchived) => {
        let title = ""
        if (isArchived === 1) {
            title = '确认归档，归档之后无法编辑，只能在归档列表中显示'
        } else {
            title = "确认撤销归档"
        }
        Modal.confirm({
            title: title,
            okText: '确认',
            cancelText: '取消',
            closable: true,
            onOk: (v) => {
                updateIsArchived(projectId, devId, isArchived)
                    .then(result => {
                        if (result?.success) {
                            message.success("操作成功")
                            setDevDetail({
                                ...devDetail,
                                isArchived: isArchived
                            })
                        } else {
                            message.success(result?.errMsg)
                        }
                    })
                return Promise.resolve()
            }
        });
    }

    const deleteItem = () => {
        Modal.confirm({
            title: '确认删除，删除之后将无法恢复',
            okText: '确认',
            cancelText: '取消',
            closable: true,
            onOk: (v) => {
                deleteDev(projectId, devId)
                    .then(result => {
                        if (result?.success) {
                            message.success("操作成功")
                            history.push(`/projects/${projectId}/dev`)
                        } else {
                            message.success(result?.errMsg)
                        }
                    })
                return Promise.resolve()
            }
        });
    }

    const devDetailRender = (<>
        <Descriptions column={1}>
            <Descriptions.Item label="内容" span={1} />
            <Descriptions.Item span={3} >
                <EditAble permission={permission}
                    isEdit={isDetailTextEditFlag}
                    onEdit={() => {
                        setIsDetailTextEditFlag(true)
                    }}
                    width="100%"
                    value={devDetail.content && devDetail.content.raw}
                    onCancel={() => {
                        setIsDetailTextEditFlag(false)
                    }}
                    onSave={() => {
                        setIsDetailTextEditFlag(false)
                    }}
                    useCustomOperate={true}
                    editComponent={
                        <RichTextEdit
                            size="small"
                            onCancel={() => {
                                setIsDetailTextEditFlag(false)
                            }}
                            onSave={updateDevContent}
                            value={devDetail.content && devDetail.content.raw}>
                        </RichTextEdit>
                    }>
                    <RichText
                        ellipsis
                        border
                        value={devDetail.content && devDetail.content.text}>
                    </RichText>
                </EditAble>
            </Descriptions.Item>
            <Descriptions.Item label="风险点" span={1} />
            <Descriptions.Item span={1} >
                <EditAble permission={permission}
                    isEdit={isRiskItemEditFlag}
                    onEdit={() => {
                        setIsRiskItemEditFlag(true)
                    }}
                    width="100%"
                    value={devDetail.riskItems}
                    onCancel={() => {
                        setIsRiskItemEditFlag(false)
                    }}
                    onSave={() => {
                        setIsRiskItemEditFlag(false)
                    }}
                    useCustomOperate={true}
                    editComponent={
                        <RiskItem.Edit defaultValue={devDetail.riskItems}
                            onCancel={() => {
                                setIsRiskItemEditFlag(false)
                            }}
                            onSave={updateRiskItems}></RiskItem.Edit>
                    }>
                    <RiskItem permission={permission} risks={devDetail.riskItems}></RiskItem>
                </EditAble>
            </Descriptions.Item>
            <Descriptions.Item span={1} />
        </Descriptions>
    </>);

    return <>
        <div className={styles.detailContainer}>
            <PageHeader
                onBack={() => history.go(-1)}
                title={<EditAble permission={permission}
                    value={devDetail.name}
                    onSave={updateName}
                    type="input">
                    {devDetail.name}
                </EditAble>}
                extra={[
                    <ActionDropdown
                        key="action"
                        className={styles.actionDropdown}
                        placement="bottomLeft"
                        actions={[
                            devDetail?.isArchived === 0 ?
                                <TextButton key="archive" type="warning" onClick={() => {
                                    updatItemIsArchived(1)
                                }}>归档</TextButton> :
                                <TextButton key="archive" type="warning" onClick={() => {
                                    updatItemIsArchived(0)
                                }}>撤销归档</TextButton>
                            ,
                            <TextButton key="delete" type="danger" onClick={() => {
                                deleteItem()
                            }}>删除</TextButton>]}
                    />
                ]}
            >
                <Descriptions column={3}>
                    <Descriptions.Item label='负责人' span={1}>
                        <EditAble permission={permission}
                            value={devDetail.userId}
                            editComponentProps={{
                                projectId: devDetail.projectId,
                                defaultOpen: true
                            }}
                            onSave={updateProjectUser}
                            type="userSelect">
                            <UserBrief user={devDetail.user}></UserBrief>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label='状态' span={1}>
                        <EditAble permission={permission}
                            value={devDetail.status}
                            editComponentProps={{
                                options: ArrayUtils.jsonToArray(PROJECT_DEV_STATUS).map(item => {
                                    return { value: item.key, label: item.value.name }
                                }),
                                defaultOpen: true
                            }}
                            onSave={updateStatus}
                            type="select">
                            <DevStatus status={devDetail.status}></DevStatus>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label='所属迭代' span={1}>
                        <EditAble permission={permission}
                            isEdit={isProdEditFlag}
                            onEdit={() => {
                                setIsProdEditFlag(true)
                            }}
                            value={devDetail?.projectProdItemId === '0' ? null : devDetail?.projectProdItemId}
                            onCancel={() => {
                                setIsProdEditFlag(false)
                            }}
                            onSave={() => {
                                setIsProdEditFlag(false)
                            }}
                            editComponent={
                                <ProjectProdSelect
                                    onSelect={(projectProdItemId, projectProdItem) => {
                                        setIsProdEditFlag(false)
                                        updateProjectProd(projectProdItemId, projectProdItem)
                                    }}
                                    projectId={projectId}
                                    defaultValue={devDetail?.projectProdItemId} />
                            }>
                            <TextButton type="text" onClick={() => {
                                if (devDetail?.projectProdItem) {
                                    history.push(`/projects/${devDetail.projectId}/prod/${devDetail?.projectProdItemId}`)
                                }
                            }}>{devDetail?.projectProdItem?.name}</TextButton>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="开始时间" span={1}>
                        <EditAble permission={permission}
                            value={devDetail.actualStartDate}
                            editComponentProps={{
                                format: "YYYY-MM-DD HH:mm"
                            }}
                            onSave={updateActualStartDate}
                            type="timePicker">
                            {`${formetTime(devDetail.actualStartDate)}`}
                        </EditAble>
                        {devDetail.planStartDate && <Tooltip placement="topLeft" title={`预计时间:${formetTime(devDetail.planStartDate)}`}><ClockCircleOutlined /></Tooltip>}
                    </Descriptions.Item>
                    <Descriptions.Item label="提测时间" span={1}>
                        <EditAble permission={permission}
                            value={devDetail.actualSubmitQaDate}
                            editComponentProps={{
                                format: "YYYY-MM-DD HH:mm"
                            }}
                            onSave={updateActualSubmitQaDate}
                            type="timePicker">
                            {`${formetTime(devDetail.actualSubmitQaDate)}`}
                        </EditAble>
                        {devDetail.planSubmitQaDate && <Tooltip placement="topLeft" title={`预计时间:${formetTime(devDetail.planSubmitQaDate)}`}><ClockCircleOutlined /></Tooltip>}
                    </Descriptions.Item>
                    <Descriptions.Item label="发布时间" span={1}>
                        <EditAble permission={permission}
                            value={devDetail.actualReleaseDate}
                            editComponentProps={{
                                format: "YYYY-MM-DD HH:mm"
                            }}
                            onSave={updateActualReleaseTime}
                            type="timePicker">
                            {`${formetTime(devDetail.actualReleaseDate)}`}
                        </EditAble>
                        {devDetail.planReleaseDate && <Tooltip placement="topLeft" title={`预计时间:${formetTime(devDetail.planReleaseDate)}`}><ClockCircleOutlined /></Tooltip>}
                    </Descriptions.Item>
                    <Descriptions.Item label="验收时间" span={1}>
                        <EditAble permission={permission}
                            value={devDetail.demandCheckDate}
                            editComponentProps={{
                                format: "YYYY-MM-DD HH:mm"
                            }}
                            onSave={updateDemandCheckDate}
                            type="timePicker">
                            {`${formetTime(devDetail.demandCheckDate)} `}
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="创建时间" span={2}>{devDetail.createTime}</Descriptions.Item>
                    <Descriptions.Item label="概述" span={3} />
                    <Descriptions.Item span={3} >
                        <EditAble permission={permission}
                            editComponentProps={{
                                rows: 4,
                                maxLength: 200,
                                showCount: true
                            }}
                            width="80%"
                            useCustomOperate={true}
                            editComponentClassName={styles.descriptionTextAreaInput}
                            onSave={updateProjectDesc}
                            value={devDetail.description}
                            type="textarea">
                            <p>
                                {devDetail.description}
                            </p>
                        </EditAble>
                    </Descriptions.Item>
                </Descriptions>
                <Tabs
                    activeKey={tabKey}
                    tabBarGutter={-8}
                    tabBarExtraContent={{
                        right: rightEntra
                    }}
                    onChange={onChangeTabSwitch}
                    className={styles.tabClass}
                >
                    <TabPane tab="内容" key="detail">
                        {devDetailRender}
                    </TabPane>
                    <TabPane tab="任务" key="task">
                        <TaskPage projectId={projectId} queryInitParams={{
                            projectItemType: "DEV",
                            projectItemId: devId
                        }}  ></TaskPage>
                    </TabPane>
                    <TabPane tab="甘特图" key="gantt">
                        <TaskGantt projectId={projectId}
                            title={`${devDetail.name} 的甘特图`}
                            description={devDetail.description}
                            projectProdId={devDetail.id}
                            queryInitParams={{
                                projectItemType: "DEV",
                                projectItemId: devId
                            }}></TaskGantt>
                    </TabPane>
                    <TabPane tab="评论" key="comment">
                        <ProjectComment projectId={projectId} bizId={devId} bizType="dev" />
                    </TabPane>
                    <TabPane tab="日志" key="log">
                        <ProjectItemLog
                            projectId={projectId}
                            itemId={devId}
                            update={projectLogUpdate}
                            renderField={(value, fieldName, isDetail) => {
                                if (fieldName === "status") {
                                    return <DevStatus status={value}></DevStatus>
                                }
                                if (fieldName === "actualStartDate") {
                                    return formetTime(value);
                                }
                                if (fieldName === "actualSubmitQaDate") {
                                    return formetTime(value);
                                }
                                if (fieldName === "actualReleaseDate") {
                                    return formetTime(value);
                                }
                                if (fieldName === "demandCheckDate") {
                                    return formetTime(value);
                                }
                                if (fieldName === "riskItems") {
                                    if (isDetail) {
                                        return <RiskItem risks={value}></RiskItem>
                                    }
                                    return "风险点";
                                }
                            }}
                            renderFieldName={(fieldName) => {
                                if (fieldName === "projectProdItemId") {
                                    return "所属迭代"
                                }
                                if (fieldName === "actualStartDate") {
                                    return "开始时间";
                                }
                                if (fieldName === "actualSubmitQaDate") {
                                    return "提测时间";
                                }
                                if (fieldName === "actualReleaseDate") {
                                    return "发布时间";
                                }
                                if (fieldName === "demandCheckDate") {
                                    return "验收时间";
                                }
                                if (fieldName === "riskItems") {
                                    return "风险点";
                                }
                            }}
                            itemType="dev" />
                    </TabPane>

                </Tabs>
            </PageHeader>
        </div>
    </>
}


export default connect(({ }) => ({
}))(DevDetail);